/*
 * Copyright (C) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "resource_interceptor_default.h"
#include "libbase64.h"

namespace ImageKnifePro {

bool ResourceInterceptorDefault::DecodeBase64(std::shared_ptr<ImageKnifeTask> task, std::string &base64Str)
{
    size_t pos = base64Str.find(";base64,");
    if (pos == std::string::npos) {
        return false;
    }

    const int offset = 8;
    int length = base64Str.size() - pos - offset;

    const size_t size = length * 3 / 4 + 1;
    char *out = static_cast<char *>(malloc(size));

    const int plainCodec = 1 << 3;
    size_t outLength = size;
    base64_decode(base64Str.c_str() + pos + offset, length, out, &outLength, plainCodec);

    task->product.imageBuffer = std::shared_ptr<uint8_t []>(reinterpret_cast<uint8_t *>(out),
                                                            [](void *data) {free(data);});
    task->product.imageLength = outLength;
    return true;
}

}